document.addEventListener('DOMContentLoaded', () => {
  // Ask the active tab to show in-page sidebar immediately
  try {
    chrome.tabs && chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const tab = tabs && tabs[0];
      if (tab && tab.id) {
        try {
          chrome.tabs.sendMessage(tab.id, { type: 'SHOW_SIDEBAR' }, () => {
            // ignore runtime.lastError if content script not injected on this page
            void chrome.runtime.lastError;
          });
        } catch {}
      }
    });
  } catch {}
  const queueList = document.getElementById('queue-list');
  const template = document.getElementById('queue-item-template');
  const statusSummary = document.getElementById('status-summary');
  const clearCompletedBtn = document.getElementById('clear-completed');
  const startBtn = document.getElementById('start-queue');
  const pauseBtn = document.getElementById('pause-queue');
  const subfolderInput = document.getElementById('base-subfolder');

  function renderQueue(queue, paused) {
    if (!queueList || !template || !statusSummary || !clearCompletedBtn) return;

    queueList.innerHTML = '';
    if (!queue || queue.length === 0) {
      statusSummary.textContent = '队列为空。';
      if (startBtn && pauseBtn) {
        // 队列为空时也允许点击“开始下载”，用于预先置为运行状态
        startBtn.disabled = false;
        pauseBtn.disabled = paused;
      }
      clearCompletedBtn.disabled = true;
      return;
    }

    let downloadingCount = 0;
    let queuedCount = 0;
    let completedCount = 0;
    let erroredCount = 0;

    for (const item of queue) {
      const itemEl = template.content.cloneNode(true).firstElementChild;
      itemEl.dataset.url = item.url;
      itemEl.dataset.status = item.status;

      const filenameEl = itemEl.querySelector('.filename');
      const progressBarFillEl = itemEl.querySelector('.progress-bar-fill');
      const statusTextEl = itemEl.querySelector('.status-text');

      filenameEl.textContent = item.filename || '获取文件名中...';
      filenameEl.title = item.filename || item.url;

      switch (item.status) {
        case 'queued':
          queuedCount++;
          statusTextEl.textContent = '排队中...';
          progressBarFillEl.style.width = '0%';
          break;
        case 'downloading':
          downloadingCount++;
          const progress = Math.round(item.progress || 0);
          statusTextEl.textContent = `下载中... ${progress}%`;
          progressBarFillEl.style.width = `${progress}%`;
          break;
        case 'completed':
          completedCount++;
          statusTextEl.textContent = '已完成';
          progressBarFillEl.style.width = '100%';
          break;
        case 'error':
          erroredCount++;
          statusTextEl.textContent = `错误: ${item.error || '未知错误'}`;
          progressBarFillEl.style.width = '100%';
          break;
      }
      queueList.appendChild(itemEl);
    }

    statusSummary.textContent = `正在下载: ${downloadingCount}, 排队中: ${queuedCount}, 已完成: ${completedCount}`;
    if (startBtn && pauseBtn) {
      const actionable = (queuedCount > 0) || (downloadingCount > 0);
      if (!actionable) {
        // 只有已完成/错误项时，允许用户再次点击开始；暂停应置灰
        startBtn.disabled = false;
        pauseBtn.disabled = true;
      } else {
        startBtn.disabled = !paused;
        pauseBtn.disabled = paused;
      }
    }
    clearCompletedBtn.disabled = (completedCount + erroredCount) === 0;
  }

  function requestUpdate() {
    chrome.runtime.sendMessage({ type: 'GET_QUEUE_STATE' }, (response) => {
      if (chrome.runtime.lastError) {
        if (statusSummary) statusSummary.textContent = '无法连接到后台服务。';
        return;
      }
      if (response && response.queue) {
        const paused = Object.prototype.hasOwnProperty.call(response, 'paused') ? !!response.paused : true;
        renderQueue(response.queue, paused);
        if (subfolderInput) {
          const incoming = response.baseSubfolder || '';
          // 仅当未聚焦或值不同才更新，避免用户正在输入时被覆盖
          if (document.activeElement !== subfolderInput && subfolderInput.value !== incoming) {
            subfolderInput.value = incoming;
          }
        }
      }
    });
  }

  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'QUEUE_UPDATED' && message.queue) {
      const paused = Object.prototype.hasOwnProperty.call(message, 'paused') ? !!message.paused : true;
      renderQueue(message.queue, paused);
    }
  });

  if (clearCompletedBtn) {
    clearCompletedBtn.addEventListener('click', () => {
      chrome.runtime.sendMessage({ type: 'CLEAR_COMPLETED_DOWNLOADS' }, () => {
        if (chrome.runtime.lastError) return; // ignore benign error
        requestUpdate();
      });
    });
  }

  if (startBtn) {
    startBtn.addEventListener('click', () => {
      chrome.runtime.sendMessage({ type: 'START_QUEUE' }, () => {
        if (chrome.runtime.lastError) return;
        requestUpdate();
      });
    });
  }
  if (pauseBtn) {
    pauseBtn.addEventListener('click', () => {
      chrome.runtime.sendMessage({ type: 'PAUSE_QUEUE' }, () => {
        if (chrome.runtime.lastError) return;
        requestUpdate();
      });
    });
  }

  if (subfolderInput) {
    subfolderInput.addEventListener('change', () => {
      let v = subfolderInput.value || '';
      // 归一化：反斜杠->斜杠；去掉盘符；去掉多余斜杠；剔除 .. 片段
      v = v.replace(/\\/g, '/');
      v = v.replace(/^[A-Za-z]:/i, '');
      v = v.replace(/\/+/g, '/');
      v = v.split('/').filter(seg => seg && seg !== '.' && seg !== '..').join('/');
      subfolderInput.value = v;
      chrome.runtime.sendMessage({ type: 'SET_BASE_SUBFOLDER', baseSubfolder: v }, () => {
        if (chrome.runtime.lastError) return;
        requestUpdate();
      });
    });
  }

  // Delegate remove button clicks
  if (queueList) {
    queueList.addEventListener('click', (e) => {
      const btn = e.target.closest && e.target.closest('.remove-btn');
      if (!btn) return;
      const itemEl = btn.closest('.queue-item');
      const url = itemEl && itemEl.dataset && itemEl.dataset.url;
      if (!url) return;
      chrome.runtime.sendMessage({ type: 'REMOVE_FROM_QUEUE', url }, () => {
        if (chrome.runtime.lastError) return;
        requestUpdate();
      });
    });
  }

  requestUpdate();
  setInterval(requestUpdate, 1500); // Poll for updates periodically
});
